package com.shop.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shop.Redis.GoodsKey;
import com.shop.Redis.OrderKey;
import com.shop.Redis.RedisService;
import com.shop.Redis.UserKey;
import com.shop.config.DateJsonValueProcessor;
import com.shop.dao.GoodsMapper;
import com.shop.dao.GoodsOrderInfoMapper;
import com.shop.dao.UserMapper;
import com.shop.pojo.*;
import com.shop.result.JsonResult;
import com.shop.service.GoodsOrderInfoService;
import com.shop.service.LoginService;
import com.shop.util.BaseUtil;
import net.sf.json.JsonConfig;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Service
public class GoodsOrderInfoServiceImpl implements GoodsOrderInfoService {

    @Autowired
    private RedisService redisService;
    @Autowired
    private GoodsOrderInfoMapper goodsOrderInfoMapper;
    @Autowired
    private GoodsMapper goodsMapper;
    @Autowired
    private LoginService loginService;
    @Autowired
    private MongoTemplate mongoTemplate;

    /*定义集合名称*/
    private static final String collectionName = "goodsOrderInfo";

    /*查询订单（多条件）*/
    @Override
    public List<GoodsOrderInfo> queryUserOrderByCondition(HttpServletRequest request, HttpServletResponse response) throws Exception {
         String data = request.getParameter("data");
        String token = request.getParameter("token");
        User user = loginService.getUserByToken(token);
        if(null == user){
            return null;
        }

        Map<String,Object> params = null;
        if(StringUtils.isNotEmpty(data)){
            params = BaseUtil.json2Map(data);
        }else{
            params = new HashMap<>();
        }

        List<GoodsOrderInfo> goodsOrderInfos = new ArrayList<>();

        /*Mysql操作*/
        //数据库中查询的数据
//        goodsOrderInfos = goodsOrderInfoMapper.queryUserOrderByCondition(params);
//
//        //redis中缓存的未支付订单
//        Map<String, String> goodsNoPays = redisService.hGetAll(OrderKey.getOrder+user.getUserId());
//        for (Map.Entry<String, String> map : goodsNoPays.entrySet()) {
//            goodsOrderInfos.add(JSON.toJavaObject(JSON.parseObject(map.getValue().toString()), GoodsOrderInfo.class));
//        }

        /*MongoDB操作*/
        Query query = new Query();
        query.fields().exclude("_id");
//        query.fields().include(collectionName);   //指定只返回的key对应value值

        for (Map.Entry<String,Object> map : params.entrySet()) {
            query.addCriteria(Criteria.where(map.getKey()).is(map.getValue()));
        }
        goodsOrderInfos = mongoTemplate.find(query, GoodsOrderInfo.class,collectionName);

        return goodsOrderInfos;
    }

    /*添加用户订单*/
    @Override
    public JsonResult addUserOrderInfo(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String data = request.getParameter("data");
        String token = request.getParameter("token");
        String dataJson = BaseUtil.toJson(data);
        GoodsOrderInfo goodsOrderInfo = JSONObject.parseObject(dataJson,GoodsOrderInfo.class);

        User user = loginService.getUserByToken(token);
        if(null == user){
            return new JsonResult(false,"该用户信息已过期，请重新登录后再操作");
        }

        /*Redis操作*/
//        Goods goods = redisService.get(GoodsKey.getGoodsDetail,goodsOrderInfo.getGoodsId(),Goods.class);
//        if (goods == null){
//            goods = goodsMapper.selectByPrimaryKey(goodsOrderInfo.getGoodsId());
//            if (goods == null){
//                return new JsonResult(false,"商品不存在，请刷新页面");
//            }
//        }

        /*MongoDB操作*/
        Query query = new Query();
        query.fields().include("goods"); //只显示购物车信息
        query.fields().exclude("_id");  //不显示MongoDB数据库中生成的id值
        query.addCriteria(Criteria.where("goodsId").is(goodsOrderInfo.getGoodsId()));

        Map<String,Object> isGoods = mongoTemplate.findOne(query, Map.class, "goods");   //查询MongoDB中单条的购物车商品数据
        if (isGoods == null || isGoods.size() == 0){
            return new JsonResult(false,"商品不存在，请刷新页面");
        }

        goodsOrderInfo.setUserId(user.getUserId());
        goodsOrderInfo.setOrderChannel((byte) 1);
        goodsOrderInfo.setStatus((byte) 0);
        goodsOrderInfo.setCreateDate(new Date());
        goodsOrderInfo.setOrderId(BaseUtil.getSID());

        /*MySQL操作*/
//        goodsOrderInfoMapper.insert(goodsOrderInfo);

        /*MongoDB操作*/
        mongoTemplate.insert(goodsOrderInfo,collectionName);

        return new JsonResult(true,"添加订单成功");
    }

    /*修改订单状态*/
    @Override
    public JsonResult updateUserOrderStatus(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String orderId = request.getParameter("orderId");
        String status = request.getParameter("status");
        String token = request.getParameter("token");
        if(StringUtils.isEmpty(orderId)){
            return new JsonResult(false,"订单号有误，请重新操作");
        }
        if(StringUtils.isEmpty(status)){
            return new JsonResult(false,"订单状态为空，请重新操作");
        }

        User user = loginService.getUserByToken(token);
        if(null == user){
            return new JsonResult(false,"该用户信息已过期，请重新登录后再操作");
        }


        /*MySQL操作*/
//        GoodsOrderInfo goodsOrderInfo = goodsOrderInfoMapper.selectByPrimaryKey(orderId);
//        goodsOrderInfo.setStatus(Byte.valueOf(status));
//        if ("1".equals(status)){
//            goodsOrderInfo.setPayDate(new Date());
//        }
//        goodsOrderInfoMapper.updateByPrimaryKey(goodsOrderInfo);

        /*MongoDB操作*/
        Query query = new Query();
        query.addCriteria(Criteria.where("orderId").is(orderId));

        Update update = new Update();
        update.set("status",Byte.valueOf(status));
        if ("1".equals(status)){
            update.set("payDate",new Date());
        }

        mongoTemplate.updateMulti(query,update,collectionName);

        return new JsonResult(true,"修改订单成功");
    }

    /*删除订单*/
    @Override
    public JsonResult deleteUserOrderById(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String orderId = request.getParameter("orderId");
        if(StringUtils.isEmpty(orderId)){
            return new JsonResult(false,"订单号有误，请重新操作");
        }

        /*MySQL操作*/
//        goodsOrderInfoMapper.deleteByPrimaryKey(orderId);

        /*MongoDB操作*/
        Query query = new Query();
        query.addCriteria(Criteria.where("orderId").is(orderId));

        GoodsOrderInfo goodsOrderInfo = mongoTemplate.findOne(query,GoodsOrderInfo.class);  //查询MongoDB数据中的单条数据
        if (goodsOrderInfo != null){    //当查询出来的数据不为空时，方可执行remove方法
            mongoTemplate.remove(query, GoodsOrderInfo.class,collectionName);
        }

        return new JsonResult(true,"删除订单成功");
    }

}
